import 'dart:io';

import 'package:flutter/material.dart';
import 'package:home_framework/view_models/dynamic/dynamic_model.dart';
import 'package:home_framework/view_models/dynamic/dynamic_share_model.dart';
import 'package:provider/provider.dart';
import 'dynamic_form.dart';

class DynamicEditWrapper extends StatelessWidget {
  final String dynamicId;
  DynamicEditWrapper(this.dynamicId, {Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider.value(
      value: DynamicShareModel.sharedDynamicModel,
      child: _DynamicEdit(dynamicId),
    );
  }
}

class _DynamicEdit extends StatefulWidget {
  final String dynamicId;
  _DynamicEdit(this.dynamicId, {Key key}) : super(key: key);

  @override
  _DynamicEditState createState() => _DynamicEditState();
}

class _DynamicEditState extends State<_DynamicEdit> {
  @override
  void initState() {
    super.initState();
    context.read<DynamicShareModel>().clearState();
    context.read<DynamicShareModel>().getDynamic(widget.dynamicId);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('编辑动态'),
        brightness: Brightness.dark,
      ),
      body: _getFormWidgets(),
    );
  }

  _getFormWidgets() {
    final watchState = context.watch<DynamicShareModel>();
    final readState = context.read<DynamicShareModel>();
    if (watchState.currentDynamic == null)
      return Center(
        child: Text('加载中...'),
      );
    return DynamicForm(
      watchState.formData,
      readState.handleTextFieldChanged,
      readState.handleClear,
      '保存',
      () {
        readState.handleEdit().then((success) {
          context.read<DynamicModel>().update(watchState.currentDynamic);
          Navigator.of(context).pop();
        });
      },
      readState.handleImagePicked,
      imageFile: watchState.imageFile,
      imageUrl: watchState.currentDynamic.imageUrl,
    );
  }
}
